<template>
  <div class="withdraw-page page-container">
    <div class="withdraw-wrapper">
      <!-- 内容区域 -->
      <div class="content">
        <!-- 账户余额卡片 -->
        <div class="balance-card">
          <div class="balance-title">当前可提现余额</div>
          <div class="balance-amount">
            <span class="currency">￥</span>
            <span class="amount">{{ accountBalance.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 提现表单 -->
        <div class="withdraw-form">
          <a-form :form="form" @submit="handleSubmit">
            <!-- 提现金额 -->
            <a-form-item label="提现金额">
              <a-input-number
                v-decorator="[
                  'amount',
                  {
                    rules: [
                      { required: true, message: '请输入提现金额' },
                      { validator: validateAmount },
                    ],
                  },
                ]"
                :min="1"
                :max="accountBalance"
                :precision="2"
                :step="100"
                style="width: 100%"
                placeholder="请输入提现金额"
              >
                <a-icon slot="prefix" type="pay-circle" />
              </a-input-number>
              <div class="amount-tips">
                <span>最低提现金额：￥1.00</span>
                <a @click="withdrawAll">全部提现</a>
              </div>
            </a-form-item>

            <!-- 收款方式 -->
            <a-form-item label="收款方式">
              <div class="payment-methods">
                <div
                  v-for="method in paymentMethods"
                  :key="method.type"
                  class="method-item"
                  :class="{ active: selectedMethod === method.type }"
                  @click="selectMethod(method.type)"
                >
                  <a-icon :type="method.icon" />
                  <span>{{ method.name }}</span>
                </div>
              </div>
            </a-form-item>

            <!-- 收款码展示 -->
            <div class="qrcode-section" v-if="selectedMethod">
              <template v-if="currentQRCode">
                <div class="qrcode-wrapper">
                  <img :src="currentQRCode" alt="收款码" />
                </div>
              </template>
              <template v-else>
                <div class="no-qrcode">
                  <a-empty description="暂未设置收款码">
                    <a-button type="primary" @click="goToQRCodeSettings">
                      去设置
                    </a-button>
                  </a-empty>
                </div>
              </template>
            </div>

            <!-- 提交按钮 -->
            <a-form-item>
              <div class="form-buttons">
                <a-button
                  type="primary"
                  html-type="submit"
                  :loading="submitting"
                  :disabled="!canSubmit"
                  block
                >
                  确认提现
                </a-button>
              </div>
            </a-form-item>
          </a-form>
        </div>

        <!-- 提现说明 -->
        <div class="withdraw-tips">
          <h4>提现说明：</h4>
          <ul>
            <li>提现金额必须大于等于1元</li>
            <li>请确保收款码正确，避免资金损失</li>
            <li>提现申请将在1-3个工作日内处理</li>
            <li>如有疑问，请联系客服</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 设置收款码弹窗 -->
    <a-modal
      v-model="qrcodeModalVisible"
      title="设置收款码"
      @ok="handleQRCodeUpload"
      :confirmLoading="uploading"
      :maskClosable="false"
      :keyboard="false"
      :destroyOnClose="true"
    >
      <div class="qrcode-upload">
        <a-upload
          name="qrcode"
          list-type="picture-card"
          class="qrcode-uploader"
          :show-upload-list="false"
          :before-upload="beforeQRCodeUpload"
          accept="image/jpeg,image/png"
          :customRequest="() => {}"
          :auto-upload="false"
          @change="handleQRCodeChange"
        >
          <div v-if="!tempQRCode">
            <a-icon type="plus" />
            <div class="ant-upload-text">上传收款码</div>
          </div>
          <img v-else :src="tempQRCode" alt="收款码" style="width: 100%" />
        </a-upload>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {
  Form,
  Input,
  Button,
  Icon,
  InputNumber,
  Modal,
  Upload,
  Empty,
  message,
} from "ant-design-vue";
import { savePaymentQRCode, getUser } from "@/api/user";
import { addWithdraw } from "@/api/withdrawal";
import { mapGetters } from "vuex";
export default {
  name: "Withdraw",
  components: {
    AForm: Form,
    AFormItem: Form.Item,
    AInput: Input,
    AInputNumber: InputNumber,
    AButton: Button,
    AIcon: Icon,
    AModal: Modal,
    AUpload: Upload,
    AEmpty: Empty,
  },
  data() {
    return {
      form: this.$form.createForm(this),
      accountBalance: 0,
      submitting: false,
      selectedMethod: "",
      qrcodeModalVisible: false,
      uploading: false,
      tempQRCode: "",
      paymentMethods: [
        { type: "alipay", name: "支付宝", icon: "alipay-circle" },
        { type: "wechat", name: "微信", icon: "wechat" },
      ],
    };
  },
  computed: {
    ...mapGetters({
      alipayQrCode: "user/alipayQrCode",
      wxQrCode: "user/wxQrCode",
      id: "user/id",
    }),
    currentQRCode() {
      const qrcode =
        this.selectedMethod === "alipay" ? this.alipayQrCode : this.wxQrCode;
      return qrcode === "null" ||
        qrcode === null ||
        qrcode === undefined ||
        qrcode === ""
        ? null
        : qrcode;
    },
    canSubmit() {
      return (
        this.selectedMethod &&
        this.currentQRCode &&
        this.form.getFieldValue("amount")
      );
    },
  },
  created() {
    getUser().then((res) => {
      this.accountBalance = res.data.balance;
    });
  },
  methods: {
    goBack() {
      this.$router.push("/user");
    },
    validateAmount(rule, value, callback) {
      if (value > this.accountBalance) {
        callback("提现金额不能大于账户余额");
      } else {
        callback();
      }
    },
    withdrawAll() {
      this.form.setFieldsValue({ amount: this.accountBalance });
    },
    selectMethod(type) {
      this.selectedMethod = type;
    },
    goToQRCodeSettings() {
      this.qrcodeModalVisible = true;
    },
    beforeQRCodeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        message.error("只能上传 JPG/PNG 格式的图片！");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error("图片必须小于 2MB！");
        return false;
      }

      // 将图片转换为base64并立即显示
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.tempQRCode = reader.result;
          resolve(false); // 阻止自动上传
        };
        reader.onerror = (error) => {
          message.error("图片转换失败");
          reject(error);
        };
      });
    },
    handleQRCodeChange(info) {
      if (info.file.status === "uploading") {
        return;
      }
      if (info.file.status === "error") {
        message.error("图片上传失败，请重试");
      }
    },
    async handleQRCodeUpload() {
      if (!this.tempQRCode) {
        message.warning("请先上传收款码");
        return;
      }

      this.uploading = true;
      try {
        const updateData = {
          id: this.id,
          wxQrCode: this.selectedMethod === "wechat" ? this.tempQRCode : "",
          alipayQrCode: this.selectedMethod === "alipay" ? this.tempQRCode : "",
        };

        const response = await savePaymentQRCode(updateData);

        if (response && response.code === 200) {
          // 更新Vuex中的收款码
          this.$store.commit("user/setQrCode", {
            type: this.selectedMethod,
            qrcode: this.tempQRCode,
          });
          message.success("收款码设置成功");
          this.qrcodeModalVisible = false;
        } else {
          throw new Error(response?.msg || "收款码设置失败");
        }
      } catch (error) {
        message.error("收款码设置失败：" + (error.message || "未知错误"));
      } finally {
        this.uploading = false;
        this.tempQRCode = "";
      }
    },
    async handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields(async (err, values) => {
        if (!err) {
          this.submitting = true;
          try {
            const params = {
              userId: this.id,
              account: this.selectedMethod === "alipay" ? "alipay" : "wechat",
              amount: values.amount,
            };
            
            const response = await addWithdraw(params);
            
            if (response && response.code === 200) {
              message.success("提现申请已提交");
              this.$router.push("/user");
            } else {
              throw new Error(response?.msg || "提现申请失败");
            }
          } catch (error) {
            message.error("提现申请失败：" + (error.message || "未知错误"));
          } finally {
            this.submitting = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.withdraw-page {
  height: 100vh;
  background: #f5f7fa;
  overflow: hidden;

  .content {
    padding: 16px;

    .balance-card {
      background: linear-gradient(135deg, #1890ff, #096dd9);
      border-radius: 12px;
      padding: 20px;
      color: #fff;
      text-align: center;
      margin-bottom: 16px;

      .balance-title {
        font-size: 14px;
        opacity: 0.9;
        margin-bottom: 8px;
      }

      .balance-amount {
        .currency {
          font-size: 20px;
          margin-right: 4px;
        }

        .amount {
          font-size: 32px;
          font-weight: 500;
        }
      }
    }

    .withdraw-form {
      background: #fff;
      border-radius: 8px;
      padding: 24px;
      margin-bottom: 16px;

      .amount-tips {
        display: flex;
        justify-content: space-between;
        margin-top: 4px;
        font-size: 12px;
        color: #8c8c8c;

        a {
          color: #1890ff;
        }
      }

      .payment-methods {
        display: flex;
        gap: 12px;

        .method-item {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          padding: 12px;
          border: 1px solid #d9d9d9;
          border-radius: 8px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            border-color: #1890ff;
          }

          &.active {
            border-color: #1890ff;
            background: #e6f7ff;
          }

          .anticon {
            font-size: 20px;
          }
        }
      }

      .qrcode-section {
        margin: 24px 0;
        text-align: center;

        .qrcode-wrapper {
          display: inline-block;
          padding: 16px;
          border: 1px solid #f0f0f0;
          border-radius: 8px;

          img {
            max-width: 200px;
            max-height: 200px;
          }
        }
      }
    }

    .withdraw-tips {
      background: #fff;
      border-radius: 8px;
      padding: 16px;

      h4 {
        color: #8c8c8c;
        font-size: 14px;
        margin-bottom: 8px;
      }

      ul {
        padding-left: 20px;
        margin: 0;

        li {
          color: #8c8c8c;
          font-size: 12px;
          line-height: 1.8;
        }
      }
    }
  }
}

.qrcode-upload {
  text-align: center;

  :deep(.ant-upload-picture-card-wrapper) {
    width: 200px;
    margin: 0 auto;
  }
}

@media screen and (max-width: 768px) {
  .withdraw-page {
    .content {
      padding: 12px;

      .withdraw-form {
        padding: 16px;
      }
    }
  }
}
</style>
